import React,{Component,lazy,Suspense} from 'react'
import {withRouter} from 'react-router-dom'
import { Toast } from 'antd-mobile'

function checkToken(OldComponent){
    class NewComponent extends Component {
        constructor(){
            super()

            this.state = {
                token:''
            }
        }

        render(){
            const {token} = this.state

            return (
                <>
                    {token && <OldComponent {...this.props} token={token} />}
                </>
            )
        }

        componentDidMount(){
            const token = localStorage.getItem('token')

            if(token){
                this.setState({
                    token
                })
            }else{
                Toast.fail('请先登录')
                this.props.history.push('/login')
            }
        }
    }

    return NewComponent
}


function lazyLoad(OldComponent){
    function NewComponent(){
        const LazyComponent = lazy(OldComponent)
        const LazyRouteComponent = withRouter(LazyComponent)

        return (

            <Suspense fallback={<div style={{
                textAlign: 'center',
                fontSize: '0.3rem'
            }}>
                正在加载中....
            </div>}>
                <LazyRouteComponent />
            </Suspense>
        )
    }

    return NewComponent
}

export {
    checkToken,
    lazyLoad
}